package com.wnhz.work.yz.alipay;

import com.wnhz.work.yz.bean.ALiBean;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class OrderInfoUtil2_0 {



    /**
     * 构造支付订单参数列表
     *
     * @param app_id
     * @param info
     * @return
     */
    public static Map<String, String> buildOrderParamMap(String app_id, ALiBean.InfoEntity info) {
        Map<String, String> keyValues = new LinkedHashMap<>();

        keyValues.put("app_id", app_id);

        keyValues.put("biz_content", "{\"timeout_express\":\"30m\",\"seller_id\":\"" + info.getSeller_id() + "\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"" + info.getTotal_fee() + "\",\"subject\":\" " + info.getSubject() + "\",\"body\":\"" + info.getBody() + "\",\"out_trade_no\":\"" + info.getOut_trade_no() + "\",\"asdadasd\":\"dssad\"}");

        keyValues.put("charset", info.get_input_charset());

        keyValues.put("method", "alipay.trade.app.pay");

        keyValues.put("sign_type", info.getSign_type());

        keyValues.put("timestamp", getTime());

        keyValues.put("version", "1.0");

        return keyValues;
    }

    /**
     * 构造支付订单参数信息
     *
     * @param map 支付订单参数
     * @return
     */
    public static String buildOrderParam(Map<String, String> map) {
        List<String> keys = new ArrayList<String>(map.keySet());
        // key排序
        // Collections.sort(keys);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = map.get(key);
            sb.append(buildKeyValue(key, value, true));
            sb.append("&");
        }


        return sb.toString();
    }

    /**
     * 拼接键值对
     *
     * @param key
     * @param value
     * @param isEncode
     * @return
     */
    private static String buildKeyValue(String key, String value, boolean isEncode) {
        StringBuilder sb = new StringBuilder();
        sb.append(key);
        sb.append("=");
        if (isEncode) {
            try {
                sb.append(URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                sb.append(value);
            }
        } else {
            sb.append(value);
        }
        return sb.toString();
    }


    /**
     * 时间
     *
     * @return
     */
    private static String getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return sdf.format(new Date());
    }

}
